<!--
 * 车费费用设置
 *
-->
<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item
                ><i
                    class="iconfont icon-stall-fee-menu"
                    style="margin: 5px; font-size: 22px"
                >
                    车位费用设置</i
                ></el-breadcrumb-item
            >
        </el-breadcrumb>

        <!-- 卡片视图区域 -->
        <el-card>
            <el-row :gutter="20">
                <el-col :span="4">
                    <el-input
                        placeholder="请输入车位类型"
                        v-model="carType"
                        clearable
                    ></el-input>
                </el-col>
                <el-col :span="3">
                    <el-button
                        size="small"
                        type="success"
                        icon="iconfont icon-search-menu"
                        style="font-size: 18px"
                        @click="getList"
                    >
                        搜索</el-button
                    >
                </el-col>
                <el-col :span="3">
                    <el-button
                        size="small"
                        type="primary"
                        icon="iconfont icon-add-button"
                        style="font-size: 18px"
                        @click="toAddFee"
                    >
                        新增价格</el-button
                    >
                </el-col>
            </el-row>

            <el-table v-loading="loading" :data="fees" border stripe>
                <el-table-column
                    width="50"
                    label="序号"
                    align="center"
                    type="index"
                ></el-table-column>
                <el-table-column label="车辆类型" prop="carType" align="center">
                </el-table-column>
                <el-table-column label="时间段" align="center">
                    <template slot-scope="scope">
                        {{ formatTimeRange(scope.row.startTime, scope.row.endTime) }}
                    </template>
                </el-table-column>
                <el-table-column
                    label="价位（元/小时）"
                    prop="money"
                    align="center"
                ></el-table-column>
                <el-table-column
                    label="价位说明"
                    prop="moneyDesc"
                    align="center"
                ></el-table-column>
                <el-table-column label="创建时间" prop="feeTime" align="center">
                    <template slot-scope="scope">
                        {{ dateFormat(scope.row.feeTime, 3) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="150">
                    <template slot-scope="scope">
                        <el-button
                            @click="toEdit(scope.row)"
                            type="primary"
                            circle
                            ><i
                                class="iconfont icon-edit-button"
                                style="font-size: 22px"
                            ></i
                        ></el-button>
                        <el-button
                            @click="deleteFee(scope.row)"
                            type="danger"
                            circle
                            ><i
                                class="iconfont icon-del-button"
                                style="font-size: 22px"
                            ></i
                        ></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 新增价格对话框 -->
        <el-dialog
            title="新增收费标准"
            :visible.sync="addFeeVisible"
            width="50%"
            center
            @close="resetFeeForm"
        >
            <el-form :model="feeForm" :rules="feeRules" ref="feeForm" label-width="100px">
                <el-form-item label="车辆类型" prop="carType">
                    <el-select v-model="feeForm.carType" placeholder="请选择车辆类型" style="width: 100%">
                        <el-option label="小型车" value="小型车"></el-option>
                        <el-option label="中型车" value="中型车"></el-option>
                        <el-option label="大型车" value="大型车"></el-option>
                        <el-option label="新能源车" value="新能源车"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="时间段" prop="timeRange">
                    <el-time-picker
                        is-range
                        v-model="timeRange"
                        range-separator="至"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        format="HH:mm"
                        value-format="HH:mm"
                        style="width: 100%"
                        @change="handleTimeRangeChange"
                    >
                    </el-time-picker>
                </el-form-item>
                <el-form-item label="价格（元/小时）" prop="money">
                    <el-input-number v-model="feeForm.money" :min="0" :step="1" :precision="2" style="width: 100%"></el-input-number>
                </el-form-item>
                <el-form-item label="价格说明" prop="moneyDesc">
                    <el-input v-model="feeForm.moneyDesc" type="textarea" :rows="2"></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="addFeeVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitFeeForm">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改价格对话框 -->
        <el-dialog
            title="车位类型价格修改"
            :visible.sync="feeShow"
            width="50%"
            center
            @close="editClose"
        >
            <el-form :model="feeEdit" :rules="feeRules" ref="feeEditForm" label-width="100px">
                <el-form-item label="车辆类型" prop="carType">
                    <el-input v-model="feeEdit.carType" disabled></el-input>
                </el-form-item>
                <el-form-item label="时间段" prop="timeRange">
                    <el-time-picker
                        is-range
                        v-model="editTimeRange"
                        range-separator="至"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        format="HH:mm"
                        value-format="HH:mm"
                        style="width: 100%"
                        @change="handleEditTimeRangeChange"
                    >
                    </el-time-picker>
                </el-form-item>
                <el-form-item label="价格（元/小时）" prop="money">
                    <el-input-number v-model="feeEdit.money" :min="0" :step="1" :precision="2" style="width: 100%"></el-input-number>
                </el-form-item>
                <el-form-item label="价格说明" prop="moneyDesc">
                    <el-input v-model="feeEdit.moneyDesc" type="textarea" :rows="2"></el-input>
                </el-form-item>
            </el-form>

            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="editClose">取 消</el-button>
                <el-button
                    type="primary"
                    @click="editCon"
                    icon="iconfont icon-r-yes"
                >
                    确认修改</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>
<script>
import axios from "axios";

// 确保使用正确的API基础URL
axios.defaults.baseURL = 'http://localhost:9271';

export default {
    data() {
        return {
            total: 0,
            loading: true,
            carType: "",
            fees: [],
            // 编辑对话框
            feeShow: false,
            feeEdit: {
                id: null,
                carType: "",
                money: "",
                moneyDesc: "",
                startTime: "",
                endTime: ""
            },
            editTimeRange: [],
            // 新增价格对话框
            addFeeVisible: false,
            feeForm: {
                carType: "",
                money: 0,
                moneyDesc: "",
                startTime: "",
                endTime: ""
            },
            timeRange: [],
            // 表单验证规则
            feeRules: {
                carType: [
                    { required: true, message: "请选择车辆类型", trigger: "change" }
                ],
                money: [
                    { required: true, message: "请输入价格", trigger: "blur" }
                ]
            }
        };
    },
    methods: {
        // 获取列表数据
        getList() {
            this.loading = true;
            axios.get("/fee-setting/list", {
                params: {
                    carType: this.carType
                }
            }).then((res) => {
                this.loading = false;
                if (res.data && res.data.flag) {
                    this.fees = res.data.data;
                } else {
                    this.$message.error(res.data.message || "获取数据失败");
                }
            }).catch((error) => {
                this.loading = false;
                console.error("获取车位费用设置失败", error);
                this.$message.error("获取数据失败，请检查网络连接或后端服务是否启动");
            });
        },
        
        // 打开编辑对话框
        toEdit(row) {
            this.feeEdit.id = row.id;
            this.feeEdit.carType = row.carType;
            this.feeEdit.money = row.money;
            this.feeEdit.moneyDesc = row.moneyDesc;
            this.feeEdit.startTime = row.startTime;
            this.feeEdit.endTime = row.endTime;
            
            // 设置时间范围
            this.editTimeRange = [row.startTime, row.endTime];
            
            this.feeShow = true;
            
            // 延迟一下，确保表单已渲染完成
            this.$nextTick(() => {
                if (this.$refs.feeEditForm) {
                    this.$refs.feeEditForm.clearValidate(); // 清除表单验证结果
                }
            });
        },
        
        // 关闭编辑对话框
        editClose() {
            this.feeEdit = {
                id: null,
                carType: "",
                money: "",
                moneyDesc: "",
                startTime: "",
                endTime: ""
            };
            this.editTimeRange = [];
            this.feeShow = false;
        },
        
        // 确认编辑
        editCon() {
            console.log("编辑时的数据:", JSON.stringify(this.feeEdit)); // 添加调试日志
            console.log("编辑时的时间范围:", JSON.stringify(this.editTimeRange)); // 添加调试日志
            
            // 首先确保startTime和endTime有值
            if (!this.feeEdit.startTime || !this.feeEdit.endTime) {
                return this.$message.warning("请选择时间段");
            }
            
            this.loading = true;
            axios.post("/fee-setting/update", this.feeEdit).then((res) => {
                this.loading = false;
                if (res.data && res.data.flag) {
                    this.$message.success("修改成功！");
                    this.getList();
                    this.editClose();
                } else {
                    this.$message.error(res.data.message || "修改失败");
                }
            }).catch((error) => {
                this.loading = false;
                console.error("修改车位费用设置失败", error);
                this.$message.error("修改失败，请检查网络连接或后端服务是否启动");
            });
        },
        
        // 处理编辑对话框时间范围变化
        handleEditTimeRangeChange(val) {
            if (val && val.length === 2) {
                this.feeEdit.startTime = val[0];
                this.feeEdit.endTime = val[1];
            } else {
                this.feeEdit.startTime = "";
                this.feeEdit.endTime = "";
            }
        },
        
        // 处理时间范围变化
        handleTimeRangeChange(val) {
            if (val && val.length === 2) {
                this.feeForm.startTime = val[0];
                this.feeForm.endTime = val[1];
            } else {
                this.feeForm.startTime = "";
                this.feeForm.endTime = "";
            }
        },
        
        // 打开新增对话框
        toAddFee() {
            this.addFeeVisible = true;
        },
        
        // 重置新增表单
        resetFeeForm() {
            this.feeForm = {
                carType: "",
                money: 0,
                moneyDesc: "",
                startTime: "",
                endTime: ""
            };
            this.timeRange = [];
            if (this.$refs.feeForm) {
                this.$refs.feeForm.resetFields();
            }
        },
        
        // 提交新增表单
        submitFeeForm() {
            console.log("新增时的数据:", JSON.stringify(this.feeForm)); // 添加调试日志
            console.log("新增时的时间范围:", JSON.stringify(this.timeRange)); // 添加调试日志
            
            this.$refs.feeForm.validate(valid => {
                if (valid) {
                    // 验证时间段
                    if (!this.feeForm.startTime || !this.feeForm.endTime) {
                        return this.$message.warning("请选择时间段");
                    }
                    
                    this.loading = true;
                    axios.post("/fee-setting/add", this.feeForm).then((res) => {
                        this.loading = false;
                        if (res.data && res.data.flag) {
                            this.$message.success("添加成功！");
                            this.getList();
                            this.addFeeVisible = false;
                            this.resetFeeForm();
                        } else {
                            this.$message.error(res.data.message || "添加失败");
                        }
                    }).catch((error) => {
                        this.loading = false;
                        console.error("添加车位费用设置失败", error);
                        this.$message.error("添加失败，请检查网络连接或后端服务是否启动");
                    });
                }
            });
        },
        
        // 删除费用
        deleteFee(row) {
            this.$confirm("此操作将永久删除该收费标准, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                this.loading = true;
                axios.get(`/fee-setting/delete?id=${row.id}`).then((res) => {
                    this.loading = false;
                    if (res.data && res.data.flag) {
                        this.$message.success("删除成功！");
                        this.getList();
                    } else {
                        this.$message.error(res.data.message || "删除失败");
                    }
                }).catch((error) => {
                    this.loading = false;
                    console.error("删除车位费用设置失败", error);
                    this.$message.error("删除失败，请检查网络连接或后端服务是否启动");
                });
            }).catch(() => {
                this.$message.info("已取消删除");
            });
        },
        
        // 格式化时间范围
        formatTimeRange(start, end) {
            if (!start || !end) return '全天';
            return `${start} - ${end}`;
        },
        
        //时间转换函数
        dateFormat(val, timeType) {
            if (!val) return '';
            
            //将字符串或长整型转为时间类型
            let date = new Date(val);
            //默认格式为'年月日 时:分:秒'
            let resultFormat = "Y年M月D日 h:m:s";
            switch (timeType) {
                case 1:
                    resultFormat = "Y年M月D日";
                    break;
                case 2:
                    resultFormat = "Y-M-D";
                    break;
                case 3:
                    resultFormat = "Y-M-D h:m:s";
                    break;
            }
            let result = formatTime(resultFormat);

            // 格式化日期，如月、日、时、分、秒保证为2位数
            function formatNumber(n) {
                n = n.toString();
                return n[1] ? n : "0" + n;
            }
            // 参数number为毫秒时间戳，format为需要转换成的日期格式
            function formatTime(format) {
                let newArr = [];
                let formatArr = ["Y", "M", "D", "h", "m", "s"];
                newArr.push(date.getFullYear());
                newArr.push(formatNumber(date.getMonth() + 1));
                newArr.push(formatNumber(date.getDate()));

                newArr.push(formatNumber(date.getHours()));
                newArr.push(formatNumber(date.getMinutes()));
                newArr.push(formatNumber(date.getSeconds()));

                for (let i in newArr) {
                    format = format.replace(formatArr[i], newArr[i]);
                }
                return format;
            }

            return result;
        },
    },
    mounted() {
        this.getList();
    },
};
</script>

<style scoped>
.el-card {
    margin-top: 15px;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
}

.el-input,
.el-select {
    margin-bottom: 15px;
}

.el-button {
    margin-left: 10px;
}

.el-input-number {
    width: 100%;
}

/* 操作按钮样式 */
.el-button--circle {
    margin: 0 5px;
}
</style>
